package com.rzx.mybackend.utils;

import com.rzx.mybackend.entity.BuyMerchandise;
import com.rzx.mybackend.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * CommonUtils
 *
 * @author renzhexian
 * @date 2025/8/14
 */
@Component
@RequiredArgsConstructor
public class CommonUtils {

    private final UserService userService;

    private final RabbitTemplate rabbitTemplate;

    @Value("${spring.rabbitmq.delayOrder.exchange_name}")
    private String DELAY_EXCHANGE_NAME;

    @Value("${spring.rabbitmq.delayOrder.routing_key}")
    private String DELAY_ROUTING_KEY;

    @Value("${spring.data.redis.key_prefix.stock_key_prefix}")
    private String MERCHANDISE_STOCK_KEY;

    private final RedissonClient redissonClient;

    /**
     * 获取当前用户id
     * @return 用户id
     */
    public Long getCurrentUserId(){
        return userService.selectUserIdByUserName(SecurityContextHolder.getContext().getAuthentication().getName());
    }

    /**
     * 获取当前用户名
     * @return 用户名
     */
    public String getCurrentUserName(){
        return SecurityContextHolder.getContext().getAuthentication().getName();
    }

    /**
     * 获取当前时间
     * @return
     */
    public LocalDateTime getCurrentTime(){
        return LocalDateTime.now();
    }

    /**
     * 发送订单过期消息
     * @param orders
     * @param delayTimeMs
     */
    public void sendOrderExpireMessage(List<BuyMerchandise> orders, long delayTimeMs) {
        MessagePostProcessor messagePostProcessor = message -> {
            // 设置消息的过期时间（TTL）
            message.getMessageProperties().setExpiration(String.valueOf(delayTimeMs));
            return message;
        };

        // 发送消息到延时队列
        rabbitTemplate.convertAndSend(DELAY_EXCHANGE_NAME, DELAY_ROUTING_KEY, orders, messagePostProcessor);
    }

    /**
     * 生成商品库存分布式锁
     * @param merchandiseId
     * @return
     */
    public RLock generateStockRedisRLock(Long merchandiseId){
        String lockKey = MERCHANDISE_STOCK_KEY + merchandiseId;
        return redissonClient.getLock(lockKey);
    }
}
